package com.android.volley.codec;

import com.android.volley.socket.IOUtil;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.security.Key;

import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;


/**
 * Created by yinzhiqun on 2015/12/7.
 * 对称加密用的秘钥
 */
public class YQKey implements Serializable{
    private static final long serialVersionUID = 1L;
    public static final String ALGORITHM = "DES";

    private byte[] appid;
    private Key secretKey;
    private long expires;

    public static YQKey deSerializeFromFile(File file){
        if (file==null||!file.exists()){
            return null;
        }

        YQKey key = null;
        try {
            ObjectInputStream is = new ObjectInputStream(new FileInputStream(file));
            key = (YQKey) is.readObject();
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return key;
    }

    public void serializeToFile(File file){
        if (file==null){
            return;
        }
        try {
            ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(file));
            os.writeObject(this);
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public YQKey setAppid(String appid) {
        byte[] bytes = appid.getBytes();
        byte[] appidLength = IOUtil.wrapInt(bytes.length);
        this.appid = new byte[bytes.length+4];

        System.arraycopy(appidLength,0,this.appid,0,4);
        System.arraycopy(bytes,0,this.appid,4,bytes.length);

        return this;
    }

    public YQKey setSecretKey(byte[] keyBytes) throws Exception {
        this.secretKey = toKey(keyBytes);
        return this;
    }

    public YQKey setExpires(long expires) {
        this.expires = expires;
        return this;
    }

    public byte[] getAppid() {
        return appid;
    }

    public Key getSecretKey() {
        return secretKey;
    }

    /**
     * 检验秘钥是否超时
     * @return
     */
    public boolean isTimeout(){
        long currentTimeMillis = System.currentTimeMillis();

        return expires - currentTimeMillis < 300000;//剩余5分钟就判定为已超时，重新获取key
    }

    /**
     * 转换密钥<br>
     *
     * @param key
     * @return
     * @throws Exception
     */
    private Key toKey(byte[] key) throws Exception {
        DESKeySpec dks = new DESKeySpec(key);
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
        SecretKey secretKey = keyFactory.generateSecret(dks);

        return secretKey;
    }

}
